<template>
<div class="share_list_wrap">
  <div class="isFixed">
    <v-header @clickE="changeCard" :select="select" :backShow="true" head-text="商券"></v-header>
    <sear-my-coup fontContent="搜索电子券名称" @cardBlur="cardBlur" @cardFocus="cardFocus" @searchCoupoon="searchCoupoon"></sear-my-coup>
  </div>
  <div class="share_list_scroll">
    <div class="share_list" v-infinite-scroll="moreLoad" infinite-scroll-disabled="loading" infinite-scroll-distance="10">
      <coupon-list v-for="(couponItem, index) in CouponData" v-if="!couponItem.delayed&&couponItem.couStat!='used'" :coupon="couponItem" :index="index" :shareBox="shareBox" :key="index" @is-checked="isChecked"></coupon-list>
    </div>
    <div class="lastInfoMore" v-if="!moreInfo" v-show="nums>2">没有更多</div>
  </div>
  <!-- 分享成功弹框 -->
  <share-success @clickBack="clickBack" v-if="successShare" :noReward="noReward"></share-success>
  <!--奖励提醒弹框-->
  <remind-modal v-if="shareInfo" :type="shareType" @close="shareInfo = false" @click_btn="share"></remind-modal>
  <!-- 奖励显示弹框 -->
  <reward-modal v-if="shareInfo1" @close="shareInfo1 = false" @OK_btn="clickBack" :defaultVal="true"  :money="usrAmt" :state="padding"></reward-modal>
</div>
</template>
<script>
import VHeader from 'src/pages/home/nav.vue'
import RemindModal from 'src/componentes/global/reward/remind.vue'
import RewardModal from 'src/componentes/global/reward/index.vue'
import searMyCoup from 'src/componentes/global/searMyCoup.vue'
import * as types from '../../../vuex/types.js'
import ShareSuccess from './success.vue'
import {
  mapGetters,
  mapState
} from 'vuex'
import {
  CellSwipe,
  Toast,
  MessageBox
} from 'mint-ui'
import CouponList from './coupon.vue'
import {
  myCoupon,
  shareMyCoupon
} from '../../../service/getData3.js'
import getData from '../../../service/getData.js'

export default {
  components: {
    VHeader,
    CouponList,
    RemindModal,
    ShareSuccess,
    searMyCoup,
    RewardModal
  },
  data() {
    return {
      checkedCou: {},
      select: false,
      currentPage: 0,
      totalPage: 0,
      noMore: true,
      CouponData: [],
      successShare: false,
      moreInfo: true,
      isFixed: true,
      couponName: '',
      shareInfo: false,
      shareInfo1: false,
      flag: true,
      status: false,
      noReward: false,
      padding: false,
      shareType:'',
      loading: true,
      nums:0 //显示电子券数量
    }
  },
  methods: {
    clickBack: function() {
      window.history.back(-1);
    },
    isChecked: async function(index, coupon, hidden) {
      let choosed // 是否已选择电子券
      this.CouponData.forEach((item, key) => {
        if (index !== key) {
          if (item.isShare) {
            this.flag = true;
            choosed = true
          } else {
            item.isShare = false
          }
        }
      })
      if (choosed) {
        let data = await MessageBox.confirm('只能选一张，是否放弃刚才选的?')
        if (!data) {
          return
        } else {
          this.CouponData.forEach((item, key) => {
            if (index !== key) {
              item.isShare = false
            }
          })
        }
      }
      if ((this.CouponData[index].shareProp && this.CouponData[index].shareLvl) || (this.CouponData[index].shareCon && this.CouponData[index].settShareLvl)) {
        if (this.flag) {  // 判断是否走奖励金弹框
          this.shareInfo = true;
          this.flag = false;
          if (this.CouponData[index].shareProp && this.CouponData[index].shareLvl) { // 一级分钱的分享
            this.shareType='button'
          } else if (this.CouponData[index].shareCon && this.CouponData[index].settShareLvl) { // 二级分钱的分享
            this.shareType='onlyTwo'
          }
          if (this.CouponData[index].verFlag == '0') { //核销后给奖励金
            this.status = false;
          } else { //核销前给奖励金
            this.status = true;
          }
        } else {
          this.shareInfo = false;
          this.flag = true;
        }
      }
      if (coupon.couStat == 'listing') {
        Toast({
          message: '此券已挂单',
          duration: 1000
        });
        return;
      } else if (coupon.delayed == 4) {
        Toast({
          message: '此券已过期',
          duration: 1000
        });
        return;
      }
      this.CouponData[index].isShare = !this.CouponData[index].isShare
      let isShare = this.CouponData[index].isShare
      if (isShare) {
        this.checkedCou = this.CouponData[index] //存放被选中的券
        let coupon = this.CouponData[index]
        this.$store.commit('shareCoup', {
          couponId: coupon.couponId,
          mchtId: coupon.mchtId,
          num: coupon.num
        })
      }
    },
    cardFocus: function() {
      this.fontContent = ""
    },
    cardBlur: function() {
      this.fontContent = "搜索电子券名称或相关店铺"
    },
    // 搜索电子券名称
    searchCoupoon: function(val) {
      this.couponName = val
      this.currentPage = 0
      this.CouponData = []
      this.moreLoad();
    },
    moreLoad: function() {
      this.noMore = false;
      this.loading=true
      let currentPage = this.currentPage + 1
      let aoData = JSON.stringify([{
        name: "iDisplayStart",
        value: currentPage
      }, {
        name: "iDisplayLength",
        "value": 10
      }])
      let that = this
      getData.myCoupons({
        // currentPage: this.currentPage + 1,
        method: 'post',
        data: {
          aoData,
          couponName: that.couponName,
          type: 1
        }
      }, that.userInfo.usrId).then(res => {
        if (res.respCode === '00') {
          let data = res.content.couponList;
          if (res.content.couponList.length < 10) {
            that.moreInfo = false;
          } else {
            that.moreInfo = true; 
            that.loading = false;
          }
          data.forEach((item, index) => {
            console.log(item)
            item.isShare = false
            //判断是否为选券状态
            if (that.select) {
              item.isCheckedCou = true
            } else {
              item.isCheckedCou = false
            }
          });

          that.CouponData = that.CouponData.concat(data)
         that.nums=that.CouponData.filter(function(x){
          	return !x.delayed&&x.couStat!='used'
          }).length
          that.totalPage = Math.ceil(res.content.total / 5)
          if (that.totalPage >= that.currentPage + 1) {
            that.currentPage += 1;
          }
        }
        that.noMore = true
      })
    },
    share() {
      this.shareInfo = false
      this.changeCard()
    },
    changeCard: function() {
      // 判断是否有券
      if (this.CouponData.length) { // 0:false
        this.select = true;
        if (this.select) { // 选券
          this.CouponData.forEach(item => {
            if (item.type2 !== 'useonly') {
              item.isCheckedCou = true
            }
          })
          // 判断是否有被选中的券
          if (this.checkedCou.isShare) {
            // 判断分享途径： 1.券友圈列表icon  2.券友圈个人详情分享btn
            if (!this.friendId) {
              this.$router.push({
                name: 'friendShare',
                params: {
                  type: '1'
                }
              })
            } else { // 券友圈详情里的分享
              shareMyCoupon({
                usrId: this.userInfo.usrId,
                couponId: this.checkedCou.couponId,
                mchtId: this.checkedCou.mchtId,
                num: 1,
                shareId: [this.friendId],
                shareType: "scan"
              }).then(res => {
                if (res.respCode === '00') {
                  this.usrAmt = res.content.usrAmt;
                  if (!res.content.usrAmt) {
                    if (res.content.verFlag == '1' || res.content.verFlag == '0') { //有奖励金机制
                      if (res.content.shareProp == 0) { //分享比例是零，无提示语
                        this.noReward = false;
                      } else {
                        this.noReward = true; //往上级分享或者分享次数达到层级限制，给提示没有奖励金
                      }
                    } else { //无奖励机制
                      this.noReward = false;
                    }
                    this.successShare = true //分享成功
                  }
                  if (res.content.usrAmt == 0) { //奖励金是零
                    if (res.content.verFlag == '1' || res.content.verFlag == '0') { //有奖励金机制
                      if (res.content.shareProp == 0) { //分享比例是零，无提示语
                        this.noReward = false;
                      } else {
                        this.noReward = true; //往上级分享或者分享次数达到层级限制，给提示没有奖励金
                      }
                    } else { //无奖励机制
                      this.noReward = false;
                    }
                    this.successShare = true //分享成功
                  } else { //奖励金不为零
                    if (res.content.ifHasShareAmt) {
                      // Toast({message: '分享成功！'})
                      if (res.content.verFlag == '0') { //核销后给奖励，添加提示语（待入账）
                        this.padding = true;
                      } else if (res.content.verFlag == '1') {
                        this.padding = false;
                      }
                      this.shareInfo1 = true; //奖励提醒
                    }
                  }
                  this.CouponData.forEach(item => {
                    item.isCheckedCou = false
                  })
                  this.$store.commit('shareCoupUser', '') //清除数据和本地存储
                  // this.currentPage = 0
                  // this.CouponData = []
                  // this.moreLoad() //刷新
                } else {
                  Toast({
                    message: res.errorInfo
                  })
                }
              })
            }
            this.select = false
          }
          /* else {
                      Toast({message: '请选择您想分享的电子券！'});
                    }*/
        }
      } else {
        Toast({
          message: '您没有电子券！'
        });
      }
    }
  },
  // watch: {
  //   myCoupon(newVal) {
  //     this.myCoupon = newVal
  //   }
  // },
  computed: {
    ...mapState({
      userInfo: state => state.user.userInfo
      // myCoupon: state => state.center.myCoupon,
    }),
    ...mapGetters(['friendId'])
  },
  beforeRouteLeave(to, from, next) {
    document.body.style.background = '';
    this.$store.commit(types.HEAD_CARD_ICON, false);
    if (to.name !== 'friendShare') { // 判断是否去分享 不是这删除数据
      this.$store.commit("shareCoup", "");
      this.$store.commit("shareCoupUser", "");
    }

    next()
  },
  created: function() {
    document.body.style.background = 'rgb(246, 87, 127)';
     this.moreLoad();
  },
  mounted: function() {
    this.$nextTick(function() {
      this.$store.commit(types.HEAD_BACK_ICON, true);
      this.$store.commit(types.HEAD_MES_ICON, false);
      this.$store.commit(types.HEAD_CARD_ICON, true);
    })
  }

}
</script>
<style scoped>
.isFixed {
  position: fixed;
  top: 0;
  z-index: 100;
  width: 100%;
}

.share_list_scroll {
  padding-top: 90px;
}

.share_list {
  padding: 1rem 0 0;
  overflow: hidden;
}

.lastInfoMore {
  color: #fff;
}
</style>
